<template>
  <div class="page-container fixed-bottom">
    <Steps v-if="type === 'detail'" :step="step" :status="status" :step-list="stepList" @showReason="rejectHandle" />
    <el-form ref="form" :model="form" :rules="rules" label-width="170px" :disabled="type === 'detail'">
      <el-form-item label="套票类型：" required>
        <el-radio-group v-model="form.ticketPackageType">
          <el-radio :label="1">同店铺内套票</el-radio>
          <el-radio :label="2">本企业下跨店铺套票</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="参加店铺：" prop="shop">
        <el-button v-if="type !=='detail'" type="primary" @click="selectShop">选择店铺</el-button>
        <div v-if="form.shopList && form.shopList.length">
          <el-tag v-for="(item,index) in form.shopList" :key="item.shopId" effect="plain" :closable="type!== 'detail'" @close="deleteTag(index)">
            {{ item.shopName }}
          </el-tag>
        </div>
      </el-form-item>
      <el-form-item label="有效时间：" prop="timeList">
        <el-date-picker
          v-model="form.timeList"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="套票产品：" prop="product">
        <el-button v-if="type !=='detail'" type="primary" @click="selectProduct">选择产品</el-button>
        <p>已选择产品数：{{ form.ticketProductBaseVOS.length }}个</p>
        <div class="ticket-item">
          <el-table border :data="form.ticketProductBaseVOS">
            <el-table-column label="产品名称" prop="productName" />
            <el-table-column label="产品规格" prop="" />
            <el-table-column label="规格单位" prop="" />
            <el-table-column label="价格（元）" prop="productPrice" />
            <el-table-column label="产品数量">
              <template slot-scope="scope">
                <el-input v-model="scope.row.productNum" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column label="套票价格（元）" prop="">
              <template slot-scope="scope">
                <el-input v-model="scope.row.packagePrice" placeholder="请输入" />
              </template>
            </el-table-column>
            <el-table-column label="店铺名称" prop="shopName" />
            <el-table-column label="项目名称" prop="projectName" />
            <el-table-column v-if="type !=='detail'" label="操作">
              <template slot-scope="scope">
                <el-button type="text" class="danger-text-button" @click="deleteProduct(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item label="套票总价：" prop="retailPrice">
        <el-input v-model="form.retailPrice" class="min-input" clearable />
      </el-form-item>
      <el-form-item label="套票库存：" prop="dailyInventory">
        <el-input v-model="form.dailyInventory" class="min-input" clearable />
      </el-form-item>
      <el-form-item label="产品图片：" prop="productImg">
        <UploadFile :file-list="form.productImg" @change="uploadHandle($event, 'productImg','productImg')">
          <div slot="tip">
            <p>建议尺寸：封面690*350px，小于1M的JPG/PNG/GIF格式的图片</p>
          </div>
        </UploadFile>
      </el-form-item>
      <el-form-item label="套票名称：" prop="name">
        <el-input v-model="form.name" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="套票简介：">
        <el-input v-model="form.introduction" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="购买须知：" prop="playInstructions">
        <el-input v-model="form.playInstructions" placeholder="请输入" type="textarea" rows="5" clearable />
      </el-form-item>
      <el-form-item label="详情" prop="illustrate">
        <RichText :value.sync="form.illustrate" :disabled="type === 'detail'" />
      </el-form-item>
      <el-form-item label="标签：">
        <el-checkbox-group v-model="form.labels">
          <el-checkbox label="0">特惠</el-checkbox>
          <el-checkbox label="1">特价</el-checkbox>
          <el-checkbox label="2">景区自营</el-checkbox>
          <el-checkbox label="3">谁买使用</el-checkbox>
          <el-checkbox label="4">每日抄底</el-checkbox>
          <el-checkbox label="5">惠民补贴</el-checkbox>
          <el-checkbox label="6">十亿补贴</el-checkbox>
          <el-checkbox label="7">无需换票</el-checkbox>
          <el-checkbox label="8">提前预定</el-checkbox>
          <el-checkbox label="9">限时抢购</el-checkbox>
          <el-checkbox label="10">全网低价</el-checkbox>
          <el-checkbox label="11">今日必买</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="套票栏目：" prop="ticketColumn">
        <el-radio-group v-model="form.ticketColumn">
          <el-radio :label="0">吃美食</el-radio>
          <el-radio :label="1">游景区</el-radio>
          <el-radio :label="2">景区门票+住宿</el-radio>
          <el-radio :label="3">镇街通票</el-radio>
          <el-radio :label="4">其他</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否支持使用优惠券：" required>
        <el-radio-group v-model="form.supportCoupon">
          <el-radio :label="0">不支持</el-radio>
          <el-radio :label="1">支持</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div v-if="type !=='detail'" class="bottom-handle-box">
      <el-button type="primary" @click="saveHandle">发布</el-button>
    </div>
    <AddShop
      v-if="showAddShop"
      :shop-type="form.ticketPackageType"
      @confirm="confirmShopHandle"
      @close="closeHandle"
    />
    <AddProduct
      v-if="showAddProduct"
      :product-list="form.ticketProductBaseVOS"
      @confirm="confirmProductHandle"
      @close="closeHandle"
    />
    <Reject
      v-if="showReject"
      :reject-form="rejectForm"
      @close="closeHandle"
    />
  </div>
</template>

<script>
import UploadFile from '@/components/UploadFile/index.vue'
import RichText from '@/components/RichText/index.vue'
import Steps from './Steps.vue'
import AddShop from './AddShop.vue'
import AddProduct from './AddProduct.vue'
import Reject from '@/components/Approve/Reject.vue'
import { createTicket, getTicketDetail } from '@/api/ticket'
import { getShopListByShopId } from '@/api/shop'

export default {
  name: 'TicketDetail',
  components: {
    Steps,
    UploadFile,
    RichText,
    AddShop,
    AddProduct,
    Reject
  },
  data() {
    const validateShop = (rule, value, callback) => {
      if (this.form.shopList.length > 0) {
        callback()
      } else {
        callback(new Error('请选择店铺'))
      }
    }
    const validateProduct = (rule, value, callback) => {
      if (this.form.ticketProductBaseVOS.length > 0) {
        this.form.ticketProductBaseVOS.map(item => {
          if (!item.productNum || !item.packagePrice) {
            callback(new Error('请选择套票产品'))
          }
        })
        callback()
      } else {
        callback(new Error('请选择套票产品'))
      }
    }
    return {
      id: '',
      type: '',
      step: 1,
      stepList: [],
      status: -1,
      rejectForm: {},
      showReject: false,
      showAddShop: false,
      showAddProduct: false,
      form: {
        ticketPackageType: 1,
        shopList: [],
        timeList: [],
        ticketProductBaseVOS: [],
        retailPrice: '',
        dailyInventory: '',
        productImg: '',
        name: '',
        introduction: '',
        playInstructions: '',
        illustrate: '',
        labels: [],
        ticketColumn: '',
        supportCoupon: 0
      },
      rules: {
        shop: [{ required: true, validator: validateShop, trigger: ['blur', 'change'] }],
        timeList: [{ required: true, message: '请选择有效时间', trigger: ['blur', 'change'] }],
        product: [{ required: true, validator: validateProduct, trigger: ['blur', 'change'] }],
        retailPrice: [{ required: true, message: '请输入套票总价', trigger: ['blur'] }],
        dailyInventory: [{ required: true, message: '请输入套票库存', trigger: ['blur'] }],
        productImg: [{ required: true, message: '请上传产品图片', trigger: ['blur', 'change'] }],
        name: [{ required: true, message: '请输入套票名称', trigger: ['blur'] }],
        playInstructions: [{ required: true, message: '请输入购买须知', trigger: ['blur'] }],
        illustrate: [{ required: true, message: '请输入套票详情', trigger: ['blur'] }],
        ticketColumn: [{ required: true, message: '请选择套票栏目', trigger: ['change'] }]
      }
    }
  },

  watch: {
    'form.ticketProductBaseVOS': {
      handler(newValue, oldValue) {
        if (newValue.length > 0) {
          let price = 0
          newValue.map(item => {
            if (Number(item.productNum) && Number(item.packagePrice)) {
              price = price + item.productNum * item.packagePrice
            }
          })
          this.form.retailPrice = price
        }
      },
      deep: true
    }
  },

  created() {
    const { id, type } = this.$route.query
    this.id = id
    this.type = type
    if (this.id) {
      this.getDetail()
    }
  },

  methods: {
    getDetail() {
      const data = {
        id: this.id
      }
      getTicketDetail(data).then(res => {
        const {
          createTime,
          accountName,
          approveTime,
          approveUserStr,
          approveStatusStr,
          approveStatus,
          rejectReason,
          rejectFileUrl,
          ticketPackageCreateReq
        } = res || {}
        this.status = approveStatus
        if (this.status === 0) {
          this.step = 1
        } else {
          this.step = 3
        }
        this.rejectForm = {
          rejectReason,
          rejectFileUrl
        }
        this.stepList = [
          {
            title: '提交申请',
            time: createTime,
            user: accountName
          },
          {
            title: '审核员审核',
            time: approveTime,
            user: approveUserStr
          },
          {
            title: '完成',
            time: approveTime,
            status: approveStatusStr
          }
        ]
        const {
          ticketPackageType,
          shopIds,
          startDate,
          endDate,
          ticketProductBaseVOS,
          retailPrice,
          dailyInventory,
          productImg,
          name,
          introduction,
          playInstructions,
          illustrate,
          labels,
          ticketColumn,
          supportCoupon
        } = ticketPackageCreateReq || {}
        this.form = {
          ticketPackageType,
          // shopList: shopIds.split(','),
          timeList: [startDate, endDate],
          ticketProductBaseVOS,
          retailPrice,
          dailyInventory,
          productImg,
          name,
          introduction,
          playInstructions,
          illustrate,
          labels: labels.split(','),
          ticketColumn,
          supportCoupon
        }
        this.getShopList(shopIds)
      }).catch(() => {})
    },

    getShopList(ids) {
      const data = {
        ids: ids.split(',')
      }
      getShopListByShopId(data).then(res => {
        this.$set(this.form, 'shopList', res || [])
      }).catch(() => {})
    },

    // 选择店铺
    selectShop() {
      this.showAddShop = true
    },

    // 确认选择店铺
    confirmShopHandle(shopList) {
      this.form.shopList = shopList
      this.closeHandle()
      this.$refs.form.validateField('shop')
    },

    // 删除店铺
    deleteTag(index) {
      this.form.shopList.splice(index, 1)
    },

    // 选择商品
    selectProduct() {
      this.showAddProduct = true
    },

    // 确认选择商品
    confirmProductHandle(productList) {
      this.form.ticketProductBaseVOS = this.form.ticketProductBaseVOS.concat(productList)
      this.closeHandle()
      this.$refs.form.validateField('product')
    },

    // 删除产品
    deleteProduct(index) {
      this.form.ticketProductBaseVOS.splice(index, 1)
    },

    // 拒绝原因
    rejectHandle() {
      this.showReject = true
    },

    // 关闭
    closeHandle() {
      this.showAddShop = false
      this.showAddProduct = false
      this.showReject = false
    },

    // 保存
    saveHandle() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const { timeList, shopList, labels } = this.form
          const [startDate, endDate] = timeList
          const shopIds = shopList.map(item => item.shopId)
          const data = {
            id: this.id,
            ticketType: 1,
            draft: false,
            ...this.form,
            startDate,
            endDate,
            shopIds: shopIds.join(','),
            labels: labels.length ? labels.join(',') : ''
          }
          console.log(data)
          createTicket(data).then(res => {
            this.$message.success('发布成功')
            this.$router.back()
          }).catch(() => {})
        } else {
          return false
        }
      })
    },

    // 上传图片
    uploadHandle(payload, name, prop) {
      const fileList = payload.fileList
      const result = []
      fileList.map(item => {
        result.push(item.url)
      })
      this.form[name] = result.join(',')
      this.$refs.form.validateField(prop)
    }
  }
}
</script>

<style lang="scss" scoped>
.ticket-item{
  margin-top: 10px;
}
.min-input{
  width: 150px;
  margin-right: 10px;
}
.el-tag{
  margin-right: 10px;
}
</style>
